import React, { useContext, useEffect, useRef, useState } from "react";
import {
  Animated,
  InteractionManager,
  Keyboard,
  Pressable,
  TextInput,
  View,
} from "react-native";
import Ionicons from "@expo/vector-icons/Ionicons";
import MaterialCommunityIcons from "@expo/vector-icons/MaterialCommunityIcons";
import FontAwesome from "@expo/vector-icons/FontAwesome";
import styles from "./index.style";
import MoreOptionsDrawer from "./MoreOptionsDrawer";
import VoiceInput from "src/components/Chat/ChatDetail/BottomBar/VoiceInput";
import { ChatInputBar } from "@/components/Chat/ChatDetail/BottomBar/ChatInputBar";
import EmojiPanelDrawer from "@/components/Chat/ChatDetail/BottomBar/EmojiPanelDrawer";
import { ChatDetailContext, DrawerType } from "@/components/Chat/ChatDetail";
import { useTheme } from "@/contexts/ThemeContext";
import { ChatMessage, MessageStatus, MessageType } from "@/types/chat-message";
import { getSnowflakeId } from "@/utils/snow-flake-utils";
import {
  useChatMessageActions,
  useChatMessageState,
} from "@/hooks/chat/chat-message";
import { useUserProfileState } from "@/hooks/user/user-profile";
import { useStompSend } from "@/hooks/stomp/stomp-send";
import {useChatSessionActions} from "@/hooks/chat/chat-session";
import {SessionType} from "@/types/chat-session";

const MemoizedEmojiPanelDrawer = React.memo(EmojiPanelDrawer);
const MemoizedMoreOptionsDrawer = React.memo(MoreOptionsDrawer);

export default function BottomBar() {
  const { colors } = useTheme();
  const { currentUser } = useUserProfileState();

  const {
    sessionId,
    sessionType,
    flatListRef,
    setShowDrawerType,
    showDrawerType,
    inputText,
    setInputText,
  } = useContext(ChatDetailContext);
  const textInputRef = useRef<TextInput>(null);
  const { reply } = useChatMessageState();
  const { setReply, addMessage } = useChatMessageActions();
  const [voiceMode, setVoiceMode] = useState(false);
  const { sendChatMessage } = useStompSend();

  const translateY = useRef(new Animated.Value(0)).current;

  const [keyboardVisible, setKeyboardVisible] = useState(false);
  const [drawerReady, setDrawerReady] = useState(false);
  const {updateSession} = useChatSessionActions()

  useEffect(() => {
    const showSub = Keyboard.addListener("keyboardDidShow", () =>
      setKeyboardVisible(true)
    );
    const hideSub = Keyboard.addListener("keyboardDidHide", () => {
      setKeyboardVisible(false);
      setTimeout(() => setDrawerReady(true), 100);
    });

    return () => {
      showSub.remove();
      hideSub.remove();
    };
  }, []);

  useEffect(() => {
    if (showDrawerType === "emoji") {
      Animated.timing(translateY, {
        toValue: 0,
        duration: 200,
        useNativeDriver: true,
      }).start();
    } else {
      Animated.timing(translateY, {
        toValue: 100,
        duration: 200,
        useNativeDriver: true,
      }).start();
    }
  }, [showDrawerType]);

  const sendMessage = async () => {
    const trimmedText = inputText.trim();
    if (!trimmedText) return;
    const msg: ChatMessage<any, any> = {
      messageId: getSnowflakeId(),
      sessionId,
      user: {
        id: currentUser.id,
        name: currentUser.nickname,
        avatar: currentUser.avatar,
        updateTime: Date.now(),
      },
      messageType: MessageType.TEXT,
      content: { text: trimmedText },
      revokeStatus: false,
      system: false,
      status: sessionType === SessionType.SINGLE && sessionId === currentUser.id ?
          MessageStatus.SENT : // 自己发送给自己的消息状态为SENT
          MessageStatus.SENDING, // 发送给其他人的消息状态为SENDING
      reply: reply || null,
      createTime: Date.now(),
    };
    InteractionManager.runAfterInteractions(async () => {
      await addMessage(msg)
      // 更新会话的最后一条消息和最后一条消息ID
      await updateSession({lastMessage: msg.content.text , lastMessageId: msg.messageId, sessionId})
      if (sessionType === SessionType.GROUP || (sessionType === SessionType.SINGLE && sessionId !== currentUser.id)) {
        sendChatMessage({...msg, sessionType});
      }
    });
    requestAnimationFrame(() => {
      setInputText("");
      flatListRef.current?.scrollToEnd({ animated: true });
      if (reply) {
        setReply(null);
      }
    });
  };

  const setDrawerType = (type: DrawerType) => {
    if (type === "keyboard" || type === showDrawerType) {
      setShowDrawerType("keyboard");
      textInputRef.current?.focus();
    } else {
      Keyboard.dismiss();
      textInputRef.current?.blur();
      setShowDrawerType(type);
      setDrawerReady(true);
    }
  };


  const onUploadSuccess = async () => {
    flatListRef.current?.scrollToEnd({ animated: true });
  };

  // 渲染发送按钮
  const renderMessageSendButton = () => {
    if (inputText.length > 0) {
      return (
          <Pressable onPress={sendMessage} style={styles.icon}>
            <MaterialCommunityIcons name="send" size={24} color="#1e90ff"/>
          </Pressable>
      );
    } else {
      return (
          <Pressable onPress={() => setDrawerType("media")} style={styles.icon}>
            <Ionicons name="add" size={24} color="gray"/>
          </Pressable>
      );
    }
  };

  // 渲染表情包发送/键盘输入按钮
  const renderEmojiButton = () => {
    if (showDrawerType === "emoji") {
      return (
          <Pressable
              onPress={() => setDrawerType("keyboard")}
              style={styles.icon}
          >
            <MaterialCommunityIcons name="keyboard" size={24} color="gray"/>
          </Pressable>
      );
    } else {
      return (
          <Pressable onPress={() => setDrawerType("emoji")} style={styles.icon}>
            <FontAwesome name="smile-o" size={24} color="gray"/>
          </Pressable>
      );
    }
  };

  // 渲染语音/键盘切换按钮
  const renderVoiceKeyboardButton = () => {
    if (voiceMode) {
      return (
          <Pressable onPress={() => setVoiceMode(false)} style={styles.icon}>
            <MaterialCommunityIcons name="keyboard" size={24} color="gray"/>
          </Pressable>
      );
    } else {
      return (
          <Pressable onPress={() => setVoiceMode(true)} style={styles.icon}>
            <FontAwesome name="microphone" size={24} color="gray"/>
          </Pressable>
      );
    }
  };

  // 修改 renderDrawer 函数，只处理表情和媒体抽屉
  const renderDrawer = () => {
    if (!showDrawerType || voiceMode) return null;

    if (!keyboardVisible && drawerReady && showDrawerType === "emoji") {
      return (
          <Animated.View style={{transform: [{translateY}]}}>
            <MemoizedEmojiPanelDrawer/>
          </Animated.View>
      )
    } else if (!keyboardVisible && drawerReady && showDrawerType === "media") {
      return (
          <MemoizedMoreOptionsDrawer onUploadSuccess={onUploadSuccess}/>
      );
    }
  };

  // 渲染输入区域 - 根据模式显示不同的输入方式
  const renderInputArea = () => {
    if (voiceMode) {
      return (
          <View style={styles.voiceInputStyles}>
            <VoiceInput
                sessionId={sessionId}
                sessionType={sessionType}
                visible={voiceMode}
                onClose={() => setVoiceMode(false)}
            />
          </View>
      );
    } else {
      return (
          <>
            <ChatInputBar
                inputText={inputText}
                setInputText={setInputText}
                ref={textInputRef}
                sessionId={sessionId}
                sessionType={sessionType}
                setShowDrawerType={setShowDrawerType}
            />
            {renderEmojiButton()}
            {renderMessageSendButton()}
          </>
      );
    }
  };

  return (
      <>
        <View style={[styles.bottomBar, {
          borderColor: colors.border.divider,
          backgroundColor: colors.background,
        }]}>
          {renderVoiceKeyboardButton()}
          {renderInputArea()}
        </View>
        {renderDrawer()}
      </>
  );
}
